<?php
/**
 * Loader file.
 *
 * For the 2.1 release, this file only serves to separate and organise content from achievements-functions.php.
 * When BuddyPress 1.3 hits, this file will hold the new BP_Component class.
 *
 * @author Paul Gibbs <paul@byotos.com>
 * @package Achievements for BuddyPress
 * @subpackage loader
 *
 * $Id$
 */

// You can override these in wp-config.php.
if ( !defined( 'DPA_SLUG' ) )
	define ( 'DPA_SLUG', __( 'achievements', 'dpa' ) );

if ( !defined( 'DPA_SLUG_CREATE' ) )
	define ( 'DPA_SLUG_CREATE', __( 'create', 'dpa' ) );

if ( !defined( 'DPA_SLUG_MY_ACHIEVEMENTS' ) )
	define ( 'DPA_SLUG_MY_ACHIEVEMENTS', __( 'unlocked', 'dpa' ) );

if ( !defined( 'DPA_SLUG_ACHIEVEMENT_EDIT' ) )
	define ( 'DPA_SLUG_ACHIEVEMENT_EDIT', __( 'edit', 'dpa' ) );

if ( !defined( 'DPA_SLUG_ACHIEVEMENT_DELETE' ) )
	define ( 'DPA_SLUG_ACHIEVEMENT_DELETE', __( 'delete', 'dpa' ) );

if ( !defined( 'DPA_SLUG_ACHIEVEMENT_GRANT' ) )
	define ( 'DPA_SLUG_ACHIEVEMENT_GRANT', __( 'give', 'dpa' ) );

if ( !defined( 'DPA_SLUG_ACHIEVEMENT_CHANGE_PICTURE' ) )
	define ( 'DPA_SLUG_ACHIEVEMENT_CHANGE_PICTURE', __( 'change-picture', 'dpa' ) );

if ( !defined( 'DPA_SLUG_ACHIEVEMENT_UNLOCKED_BY' ) )
	define ( 'DPA_SLUG_ACHIEVEMENT_UNLOCKED_BY', __( 'unlocked-by', 'dpa' ) );

if ( !defined( 'DPA_SLUG_ACHIEVEMENT_ACTIVITY' ) )
	define ( 'DPA_SLUG_ACHIEVEMENT_ACTIVITY', __( 'home', 'dpa' ) );

if ( !defined( 'DPA_SLUG_ACHIEVEMENT_ACTIVITY_RSS' ) )
	define ( 'DPA_SLUG_ACHIEVEMENT_ACTIVITY_RSS', __( 'feed', 'dpa' ) );

if ( !defined( 'DPA_SLUG_ADMIN_SUPPORT' ) )
	define ( 'DPA_SLUG_ADMIN_SUPPORT', __( 'support', 'dpa' ) );

/**
 * Version number
 */
define ( 'ACHIEVEMENTS_VERSION', '2.1' );

load_plugin_textdomain( 'dpa', false, '/achievements/includes/languages/' );

// Functions
require_once ( dirname( __FILE__ ) . '/achievements-functions.php' );

// Cache management
require_once ( dirname( __FILE__ ) . '/achievements-cache.php' );

// Template & RSS output
require_once ( dirname( __FILE__ ) . '/achievements-actions.php' );
require_once ( dirname( __FILE__ ) . '/achievements-screens.php' );

// Database access classes and functions
require_once ( dirname( __FILE__ ) . '/achievements-classes.php' );

// Functions used in AJAX queries
require_once ( dirname( __FILE__ ) . '/achievements-ajax.php' );

// Enqueue CSS and JS files
require_once ( dirname( __FILE__ ) . '/achievements-cssjs.php' );

// Classes and functions designed for use in template files
require_once ( dirname( __FILE__ ) . '/achievements-template.php' );

// Widgets
require_once ( dirname( __FILE__ ) . '/achievements-widgets.php' );

// Activity stream support and email notification functions
require_once ( dirname( __FILE__ ) . '/achievements-notifications.php' );

// Component output filters
require_once ( dirname( __FILE__ ) . '/achievements-filters.php' );

/**
 * Register post types
 *
 * @since 2.1
 */
function dpa_register_post_types() {
	$achievements_labels = array(
		'add_new'            => _x( 'Add New', 'achievement',          'dpa' ),
		'add_new_item'       => __( 'Add New Achievement',             'dpa' ),
		'all_items'          => __( 'All Achievements',                'dpa' ),
		'edit'               => _x( 'Edit',    'achievement',          'dpa' ),
		'edit_item'          => __( 'Edit Achievement',                'dpa' ),
		'name'               => __( 'Achievements',                    'dpa' ),
		'new_item'           => __( 'New Achievement',                 'dpa' ),
		'not_found'          => __( 'No achievements found.',          'dpa' ),
		'not_found_in_trash' => __( 'No achievements found in Trash.', 'dpa' ),
		'search_items'       => __( 'Search Achievements',             'dpa' ),
		'singular_name'      => __( 'Achievement',                     'dpa' ),
		'view'               => __( 'View Achievement',                'dpa' ),
		'view_item'          => __( 'View Achievement',                'dpa' )
	);

	// Achievements
	$achievements  = apply_filters( 'dpa_register_post_type_achievements', array(
		'hierarchical'         => true,
		'labels'               => $achievements_labels,
		'public'               => false,
		'query_var'            => false,
		'register_meta_box_cb' => 'dpa_admin_achievements_cb',
		'rewrite'              => false,
		'show_ui'              => true,
		'supports'             => array( 'editor', 'revisions', 'title', 'thumbnail' )
	) );
	register_post_type( 'dpa_achievements', $achievements );
}
add_action( 'init', 'dpa_register_post_types', 8 );

/**
 * Register post statuses
 *
 * @since 2.1
 */
function dpa_register_post_statuses() {
}
add_action( 'init', 'dpa_register_post_statuses', 8 );

/**
 * Register custom taxonomies
 *
 * The 'dpa_action' taxonomy is used by the Achievements custom post type to
 * associate an action with the achievement.
 *
 * @since 2.1
 */
function dpa_register_taxonomies() {
	$action_labels = array(
		'name'          => _x( 'Events', 'event taxonomy general name', 'dpa' ),
		'singular_name' => _x( 'Event', 'event taxonomy singular name', 'dpa' ),
		'search_items'  => __( 'Search Events',                         'dpa' ),
		'popular_items' => __( 'Popular Events',                        'dpa' ),
		'all_items'     => __( 'All',                                   'dpa' ),
		'edit_item'     => __( 'Edit Event',                            'dpa' ),
		'update_item'   => __( 'Update Event',                          'dpa' ),
		'add_new_item'  => __( 'Add New Event',                         'dpa' ),
		'new_item_name' => __( 'New Event Name',                        'dpa' )
	);

	$action = apply_filters( 'dpa_register_taxonomy_action', array(
		'hierarchical'          => true,
		'labels'                => $action_labels,
		'public'                => false,
		'query_var'             => false,
		'rewrite'               => false,
		'show_tagcloud'         => false,
		'show_ui'               => true,
		'update_count_callback' => '_update_post_term_count'
	) );
	register_taxonomy( 'dpa_action', 'dpa_achievements', $action );
}
add_action( 'init', 'dpa_register_taxonomies', 9 );

/**
 * Install default achievement data into the database.
 *
 * @since 2.1
 * @global wpdb $wpdb WordPress database object
 */
function dpa_install() {
	global $wpdb;

	if ( !is_super_admin() )
		return;

	$user_id = get_current_user_id();

	$actions   = array();
	$actions[] = array( 'blog',            'comment_post',                         __( 'The user writes a comment on a post or page.', 'dpa' ),                             0 );
	$actions[] = array( 'blog',            'draft_to_publish',                     __( 'The user publishes a post or page.', 'dpa' ),                                       0 );
	$actions[] = array( 'members',         'friends_friendship_requested',         __( 'The user sends a friendship request to someone.', 'dpa' ),                          0 );
	$actions[] = array( 'groups',          'groups_invite_user',                   __( 'The user invites someone to join a group.', 'dpa' ),                                1 );
	$actions[] = array( 'groups',          'groups_join_group',                    __( 'The user joins a group.', 'dpa' ),                                                  1 );
	$actions[] = array( 'groups',          'groups_promoted_member',               __( 'The user promotes a group member to a moderator or administrator.', 'dpa' ),        1 );
	$actions[] = array( 'messaging',       'messages_message_sent',                __( 'The user sends or replies to a private message.', 'dpa' ),                          0 );
	$actions[] = array( 'profile',         'xprofile_updated_profile',             __( 'The user updates their profile.', 'dpa' ),                                          0 );
	$actions[] = array( 'blog',            'bp_core_activated_user',               __( 'A new user activates their account.', 'dpa' ),                                      0 );
	$actions[] = array( 'profile',         'xprofile_avatar_uploaded',             __( "The user changes their profile's avatar.", 'dpa' ),                                 0 );
	$actions[] = array( 'members',         'friends_friendship_accepted',          __( 'The user accepts a friendship request from someone.', 'dpa' ),                      0 );
	$actions[] = array( 'members',         'friends_friendship_rejected',          __( 'The user rejects a friendship request from someone.', 'dpa' ),                      0 );
	$actions[] = array( 'blog',            'trashed_post',                         __( 'The user trashes a post or page.', 'dpa' ),                                         0 );
	$actions[] = array( 'messaging',       'messages_delete_thread',               __( 'The user deletes a private message.', 'dpa' ),                                      0 );
	$actions[] = array( 'members',         'friends_friendship_deleted',           __( 'The user cancels a friendship.', 'dpa' ),                                           0 );
	$actions[] = array( 'groups',          'groups_create_group',                  __( 'The user creates a group.', 'dpa' ),                                                0 );
	$actions[] = array( 'groups',          'groups_leave_group',                   __( 'The user leaves a group.', 'dpa' ),                                                 1 );
	$actions[] = array( 'groups',          'groups_delete_group',                  __( 'The user deletes a group.', 'dpa' ),                                                0 );
	$actions[] = array( 'forum',           'groups_new_forum_topic',               __( 'The user creates a new group forum topic.', 'dpa' ),                                1 );
	$actions[] = array( 'forum',           'groups_new_forum_topic_post',          __( 'The user replies to a group forum topic.', 'dpa' ),                                 1 );
	$actions[] = array( 'forum',           'groups_delete_group_forum_post',       __( 'The user deletes a group forum post.', 'dpa' ),                                     1 );
	$actions[] = array( 'forum',           'groups_delete_group_forum_topic',      __( 'The user deletes a group forum topic.', 'dpa' ),                                    1 );
	$actions[] = array( 'forum',           'groups_update_group_forum_post',       __( 'The user modifies a group forum post.', 'dpa' ),                                    1 );
	$actions[] = array( 'forum',           'groups_update_group_forum_topic',      __( 'The user modifies a group forum topic.', 'dpa' ),                                   1 );
	$actions[] = array( 'activitystream',  'bp_groups_posted_update',              __( "The user writes a message in a group's activity stream.", 'dpa' ),                  1 );
	$actions[] = array( 'activitystream',  'bp_activity_posted_update',            __( 'The user writes a message in their activity stream.', 'dpa' ),                      0 );
	$actions[] = array( 'activitystream',  'bp_activity_comment_posted',           __( 'The user replies to any item in any activity stream.', 'dpa' ),                     0 );
	$actions[] = array( 'multisite',       'signup_finished',                      __( 'The user creates a new site.', 'dpa' ),                                             0 );
	$actions[] = array( 'achievements',    'dpa_points_incremented',               __( 'The user is awarded points by unlocking an Achievement.', 'dpa' ),                  0 );
	$actions[] = array( 'achievements',    'dpa_achievement_unlocked',             __( 'The user unlocks an Achievement.', 'dpa' ),                                         0 );
	$actions[] = array( 'eventpress',      'publish_ep_event',                     __( 'The user publishes an event.', 'dpa' ),                                             0 );
	$actions[] = array( 'eventpress',      'reg_approved_ep_reg',                  __( 'The user registers to attend an event.', 'dpa' ),                                   0 );
	$actions[] = array( 'bpprivacy',       'bp_privacy_update_privacy_settings',   __( 'The user updates their privacy settings.', 'dpa' ),                                 0 );
	$actions[] = array( 'bpmoderation',    'bp_moderation_content_status_changed', __( 'When the reported content is moderated by an administrator', 'dpa' ),               0 );
	$actions[] = array( 'activitystream',  'bp_activity_add_user_favorite',        __( 'The user marks any item in any activity stream as a favourite.', 'dpa' ),           0 );
	$actions[] = array( 'activitystream',  'bp_activity_remove_user_favorite',     __( 'The user removes a favourited item from any activity stream.', 'dpa' ),             0 );
	$actions[] = array( 'bpmoderation',    'bp_moderation_content_flagged',        __( 'The user flags any content as inappropriate.', 'dpa' ),                             0 );
	$actions[] = array( 'bpmoderation',    'bp_moderation_content_unflagged',      __( 'The user unflags content that was previously marked as inappropriate.', 'dpa' ),    0 );
	$actions[] = array( 'groups',          'groups_demoted_member',                __( 'The user demotes a group member from a moderator or administrator.', 'dpa' ),       1 );
	$actions[] = array( 'groups',          'groups_banned_member',                 __( 'The user bans a member from a group.', 'dpa' ),                                     1 );
	$actions[] = array( 'groups',          'groups_unbanned_member',               __( 'The user unbans a member from a group.', 'dpa' ),                                   1 );
	$actions[] = array( 'groups',          'groups_premote_member',                __( 'The user receives a promotion to group moderator or administrator.', 'dpa' ),       1 );
	$actions[] = array( 'groups',          'groups_demote_member',                 __( 'The user receives a demotion from group moderator or administrator.', 'dpa' ),      1 );
	$actions[] = array( 'buddystream',     'buddystream_twitter_activated',        __( 'The user successfully authorises and connects to their Twitter account.', 'dpa' ),  0 );
	$actions[] = array( 'buddystream',     'buddystream_facebook_activated',       __( 'The user successfully authorises and connects to their Facebook account.', 'dpa' ), 0 );
	$actions[] = array( 'buddystream',     'buddystream_lastfm_activated',         __( 'The user connects to their Last.fm account.', 'dpa' ),                              0 );
	$actions[] = array( 'buddystream',     'buddystream_youtube_activated',        __( 'The user connects to their YouTube account.', 'dpa' ),                              0 );
	$actions[] = array( 'buddystream',     'buddystream_flickr_activated',         __( 'The user connects to their Flickr account.', 'dpa' ),                               0 );
	$actions[] = array( 'inviteanyone',    'accepted_email_invite',                __( 'A new user activates their account.', 'dpa' ),                                      0 );
	$actions[] = array( 'inviteanyone',    'sent_email_invite',                    __( 'The user invites someone to join the site.', 'dpa' ),                               0 );
	$actions[] = array( 'buddypresslinks', 'bp_links_cast_vote_success',           __( 'The user votes on a link.', 'dpa' ),                                                0 );
	$actions[] = array( 'buddypresslinks', 'bp_links_delete_link',                 __( 'The user deletes a link.', 'dpa' ),                                                 0 );
	$actions[] = array( 'buddypresslinks', 'bp_links_posted_update',               __( 'The user writes a comment on a link.', 'dpa' ),                                     0 );
	$actions[] = array( 'buddypresslinks', 'bp_links_create_complete',             __( 'The user creates a link.', 'dpa' ),                                                 0 );
	$actions[] = array( 'jes',             'events_event_create_complete',         __( 'The user creates an event.', 'dpa' ),                                               0 );
	$actions[] = array( 'jes',             'events_join_event',                    __( 'The user registers to attend an event.', 'dpa' ),                                   0 );
	$actions[] = array( 'jes',             'events_leave_event',                   __( 'The user cancels their registration to an event.', 'dpa' ),                         0 );
	$actions[] = array( 'jes',             'events_event_deleted',                 __( 'The user deletes an event.', 'dpa' ),                                               0 );
	$actions[] = array( 'blog',            'wp_login',                             __( 'The user logs in to the site.', 'dpa' ),                                            0 );
	$actions[] = array( 'wpsc',            'wpsc_set_cart_item',                   __( 'The user adds an item to their cart', 'dpa' ),                                      0 );

	foreach ( $actions as $action ) {
		$args  = apply_filters( 'dpa_install_action_taxonomy', array( 
			'description' => $action[0],
			'slug'        => $action[1]
		), $action );
		wp_insert_term( $action[2], 'dpa_action', $args );
	}
}

/**
 * Migrate database structure from custom tables to custom post types and taxonomies.
 *
 * One-off event, fires as part of the install/upgrade process from a pre-2.1 release to a 2.1 (or later) release.
 *
 * @since 2.1
 * @global object $bp BuddyPress global settings
 * @global wpdb $wpdb WordPress database object
 */
function dpa_upgrade_to_cpt() {
	global $bp, $wpdb;

	if ( !is_super_admin() )
		return;

	dpa_install();

	return; //temp, to avoid hurting anyone testing trunk

	if ( !$table_prefix = $bp->table_prefix )
		$table_prefix = apply_filters( 'bp_core_get_table_prefix', $wpdb->base_prefix );

	$sql   = array();
	$sql[] = "DROP TABLE IF EXISTS {$table_prefix}achievements";
	$sql[] = "DROP TABLE IF EXISTS {$table_prefix}achievements_unlocked";
	$sql[] = "DROP TABLE IF EXISTS {$table_prefix}achievements_actions";

	// Todo: usermeta

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
}

/**
 * Register actions for custom wp-admin console screens.
 *
 * @global object $bp BuddyPress global settings
 * @since 2.1
 */
function dpa_setup_admin_menu() {
	global $bp;

	if ( !$bp->loggedin_user->is_super_admin )
		return;

	require_once ( dirname( __FILE__ ) . '/admin/general.php' );
	add_action( 'load-post-new.php', 'dpa_admin_load_admin_menu' );
	add_action( 'load-post.php', 'dpa_admin_load_admin_menu' );
}
add_action( is_multisite() ? 'network_admin_menu' : 'admin_menu', 'dpa_setup_admin_menu' );

/**
 * Set up global variables
 *
 * @global object $bp BuddyPress global settings
 * @since 2.0
 */
function dpa_setup_globals() {
	global $bp;

	$bp->achievements->id                           = 'achievements';
	$bp->achievements->slug                         = DPA_SLUG;
	$bp->achievements->table_achievements           = $bp->table_prefix . 'achievements';
	$bp->achievements->table_unlocked               = $bp->table_prefix . 'achievements_unlocked';
	$bp->achievements->table_actions                = $bp->table_prefix . 'achievements_actions';
	$bp->achievements->format_notification_function = 'dpa_format_notifications';
	$bp->active_components[$bp->achievements->slug] = $bp->achievements->id;
}
add_action( 'bp_setup_globals', 'dpa_setup_globals' );

/**
 * Registers as a root component (example.com/achievements/)
 *
 * @since 2.0
 */
function dpa_setup_root_component() {
	bp_core_add_root_component( DPA_SLUG );
}
add_action( 'bp_setup_root_components', 'dpa_setup_root_component' );

/**
 * Set up navigation and register pages
 *
 * @global object $bp BuddyPress global settings
 * @global bool $is_member_page If we are under anything with a members slug
 * @since 2.0
 * @uses DPA_Achievement
 */
function dpa_setup_nav() {
	global $bp, $is_member_page;

	$url = dpa_get_achievements_permalink() . '/';

	if ( $bp->current_component == $bp->achievements->slug && $bp->achievements->current_achievement = new DPA_Achievement( array( 'type' => 'single', 'slug' => apply_filters( 'dpa_get_achievement_slug', $bp->current_action ) ) ) ) {
		if ( isset( $bp->achievements->current_achievement->is_active ) && !$bp->achievements->current_achievement->is_active && !dpa_permission_can_user_edit() ) {
			// Require edit permission to view an inactive Achievement's pages
			bp_core_redirect( dpa_get_achievements_permalink() );
			return;

		} else {
			if ( $bp->achievements->current_achievement->id )
				$bp->is_single_item = true;

			$bp->is_item_admin = 0;
			if ( $bp->loggedin_user->is_super_admin )
				$bp->is_item_admin = 1;  // Possibly redundant since BP 1.1, but left for compatibility just in case
		}
	}

	// Add 'Achievements' to the main navigation
	bp_core_new_nav_item( array( 'name' => sprintf( __( 'Achievements <span>(%s)</span>', 'dpa' ), dpa_get_total_achievement_count_for_user() ), 'slug' => $bp->achievements->slug, 'position' => 80, 'screen_function' => 'dpa_screen_my_achievements', 'default_subnav_slug' => DPA_SLUG_MY_ACHIEVEMENTS, 'item_css_id' => $bp->achievements->id ) );

	$subnav_url = $bp->loggedin_user->domain . DPA_SLUG . '/';
	bp_core_new_subnav_item( array( 'name' => sprintf( __( 'My Achievements <span>(%s)</span>', 'dpa' ), dpa_get_total_achievement_count_for_user() ), 'slug' => DPA_SLUG_MY_ACHIEVEMENTS, 'parent_url' => $subnav_url, 'parent_slug' => $bp->achievements->slug, 'screen_function' => 'dpa_screen_my_achievements', 'position' => 10, 'item_css_id' => 'achievements_my' ) );

 	if ( $bp->current_component == $bp->achievements->slug ) {
		if ( bp_is_my_profile() && !$bp->is_single_item ) {
			$bp->bp_options_title = __( 'My Achievements', 'dpa' );

		} elseif ( !bp_is_my_profile() && !$bp->is_single_item ) {
			$bp->bp_options_title = $bp->displayed_user->fullname;

		} elseif ( $bp->is_single_item ) {
			// When in a single listing, the first action is bumped down one because of the listing ID, so we need to adjust this and set the listing name to current_item.
			$bp->current_item = $bp->current_action;

			if ( isset( $bp->action_variables[0] ) )
				$bp->current_action = $bp->action_variables[0];
			else
				$bp->current_action = '';

			array_shift( $bp->action_variables );

			$bp->bp_options_title = apply_filters( 'dpa_get_achievement_name', $bp->achievements->current_achievement->name );
			$achievement_link = $url . $bp->achievements->current_achievement->slug . '/';

			// Reset the existing subnav items
			bp_core_reset_subnav_items( $bp->achievements->slug );

			// Add a new default subnav item for when the Achievements nav is selected
			bp_core_new_nav_default( array( 'parent_slug' => $bp->achievements->slug, 'screen_function' => 'dpa_screen_achievement_activity', 'subnav_slug' => DPA_SLUG_ACHIEVEMENT_ACTIVITY ) );

			// Add the subnav items which will always appear
			bp_core_new_subnav_item( array( 'name' => __( 'Home', 'dpa' ), 'slug' => DPA_SLUG_ACHIEVEMENT_ACTIVITY, 'parent_url' => $achievement_link, 'parent_slug' => $bp->achievements->slug, 'screen_function' => 'dpa_screen_achievement_activity', 'position' => 20, 'item_css_id' => 'achievements_activity' ) );
			bp_core_new_subnav_item( array( 'name' => sprintf( __( 'Unlocked By (%s)', 'dpa' ), dpa_get_achievement_unlocked_count( $bp->achievements->current_achievement->id ) ), 'slug' => DPA_SLUG_ACHIEVEMENT_UNLOCKED_BY, 'parent_url' => $achievement_link, 'parent_slug' => $bp->achievements->slug, 'screen_function' => 'dpa_screen_achievement_unlocked_by', 'position' => 40, 'item_css_id' => 'unlockedby' ) );

			if ( dpa_permission_can_user_change_picture() )
		  	bp_core_new_subnav_item( array( 'name' => __( 'Change Picture', 'dpa' ), 'slug' => DPA_SLUG_ACHIEVEMENT_CHANGE_PICTURE, 'parent_url' => $achievement_link, 'parent_slug' => $bp->achievements->slug, 'screen_function' => 'dpa_screen_achievement_change_picture', 'position' => 50, 'user_has_access' => ( dpa_permission_can_user_change_picture() ), 'item_css_id' => 'achievements_changepicture' ) );

			if ( dpa_permission_can_user_delete() )
		  	bp_core_new_subnav_item( array( 'name' => __( 'Delete', 'dpa' ), 'slug' => DPA_SLUG_ACHIEVEMENT_DELETE, 'parent_url' => $achievement_link, 'parent_slug' => $bp->achievements->slug, 'screen_function' => 'dpa_screen_achievement_delete', 'position' => 50, 'user_has_access' => ( dpa_permission_can_user_delete() ), 'item_css_id' => 'achievements_delete' ) );

			if ( dpa_permission_can_user_edit() )
		  	bp_core_new_subnav_item( array( 'name' => __( 'Edit', 'dpa' ), 'slug' => DPA_SLUG_ACHIEVEMENT_EDIT, 'parent_url' => $achievement_link, 'parent_slug' => $bp->achievements->slug, 'screen_function' => 'dpa_screen_achievement_edit', 'position' => 60, 'user_has_access' => ( dpa_permission_can_user_edit() ), 'item_css_id' => 'achievements_edit' ) );

			if ( dpa_permission_can_user_grant() )
		  	bp_core_new_subnav_item( array( 'name' => __( 'Give', 'dpa' ), 'slug' => DPA_SLUG_ACHIEVEMENT_GRANT, 'parent_url' => $achievement_link, 'parent_slug' => $bp->achievements->slug, 'screen_function' => 'dpa_screen_achievement_grant', 'position' => 70, 'user_has_access' => ( dpa_permission_can_user_grant() ), 'item_css_id' => 'achievements_grant' ) );
		}
	}
}
//add_action( 'bp_setup_nav', 'dpa_setup_nav' );

/**
 * Load template filter; allows site/super admin to override Achievements' templates in
 * their active theme and replace the ones that are stored in the plugin directory.
 *
 * @global object $bp BuddyPress global settings
 * @param string $found_template Contains any matches found for the requested template(s)
 * @param array $templates Page template(s) we want to load
 * @return string Absolute directory path to the requested template
 * @since 2.0
 */
function dpa_load_template_filter( $found_template, $templates ) {
	global $bp;

	if ( $bp->current_component != $bp->achievements->slug || $found_template )
		return $found_template;

	$filtered_templates = array();
	$filtered_templates = locate_template( $templates, false );

	if ( is_array( $filtered_templates ) && isset( $filtered_templates[0] ) && $filtered_templates[0] )
		return apply_filters( 'dpa_load_template_filter', $filtered_templates[0] );

	$filtered_templates = array();
	foreach ( (array) $templates as $template ) {
		$url = dirname( __FILE__ ) . '/templates/' . $template;

		if ( file_exists( $url ) )
			$filtered_templates[] = $url;
	}

	if ( !isset( $filtered_templates[0] ) )
		$filtered_templates[0] = '';

	return apply_filters( 'dpa_load_template_filter', $filtered_templates[0] );
}
add_filter( 'bp_located_template', 'dpa_load_template_filter', 10, 2 );

/**
 * Includes, into page output, a template file. To be used within a template included by bp_core_load_template().
 *
 * If the requested template follows the BuddyPress core theme file structure, for example "[groups]/[single]/file.php"
 * i.e. being a file of a registered root component underneath its "single" folder, we'll also try to match against a version
 * of that template path suffixed with the identifier of the object of the current component.
 *
 * For example, on pages of a group named "snugglewugglepants", we'd look for "groups/single/file-snugglewugglepants.php"
 * as well as plain-old "groups/single/file.php".
 *
 * Underneath the member page hierarchy, the user's login name is used, e.g. "members/single/page-admin.php" for the admin user.
 *
 * @global object $bp BuddyPress global settings
 * @param array $templates Requested templates, in priority order
 * @see bp_core_add_root_component()
 * @see bp_core_load_template()
 * @since 2.0
 */
function dpa_load_template( $templates ) {
	global $bp;

	// Until BuddyPress gets better template filtering, support GenesisConnect.
	if ( function_exists( 'gconnect_locate_template' ) && $templates == array( 'members/single/member-header.php' ) ) {
		gconnect_locate_template( $templates, true );
		return;
	}

	$alternative_templates = array();

	foreach ( $templates as $template ) {
		$uri = explode( '/', $template );
		$uri_size = count( $uri );

		if ( !is_array( $uri ) || $uri_size < 2 )
			continue;

		if ( '/' == $uri[0] ) {
			unset( $uri[0] );
			$uri = array_merge( $uri, array() );  // Reset the keys by merging with an empty array
		}

		if ( !in_array( $uri[0], $bp->root_components ) || 'single' != $uri[1] )
			continue;

		if ( $bp->current_item )
			$template_slug = $bp->current_item;
		elseif ( BP_MEMBERS_SLUG == $uri[0] && isset( $bp->displayed_user ) )
			$template_slug = $bp->displayed_user->userdata->user_login;
		else
			continue;

		$extension = strpos( $uri[$uri_size - 1], '.php' );
		if ( false === $extension )
			continue;

		$template_slug = apply_filters( 'dpa_load_template_slug', $template_slug, $template, $templates );
		if ( $template_slug ) {
			// Reconstruct the URL with the filename suffix
			$uri[$uri_size - 1] = substr( $uri[$uri_size - 1], 0, $extension ) . "-{$template_slug}.php";
			$alternative_templates[] = implode( '/', $uri );
		}
	}

	$templates = array_merge( apply_filters( 'dpa_load_template_alternatives', $alternative_templates, $templates ), $templates );
	if ( $located_template = apply_filters( 'bp_located_template', locate_template( $templates, false ), $templates, $alternative_templates ) )
		load_template( apply_filters( 'bp_load_template', $located_template ) );
}
?>